package com.zipking.cloud.springbootmybatis.util;

import cn.hutool.core.util.NumberUtil;
import com.zipking.cloud.springbootmybatis.persistance.entity.MsgLog;
import com.zipking.cloud.springbootmybatis.service.ThreadTableDataQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
 @Component
public class ThreadPoolUtils<T> {

    /**
     * 定义十个线程
     */
    //private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());

     /**
      * 多线程查全表(通用)
      * 注解@Async线程方法
      *
      * @param totalNum
      * @param threadAsyncTableDataQuery
      * @return
      * @throws Exception
      */
     public   List<T> threadAsync(int totalNum, ThreadTableDataQuery threadAsyncTableDataQuery) throws Exception {

         List<Future<List<T>>> list = new ArrayList<>();
         if (totalNum > 10) {
             int remainder = totalNum % 10;
             int size = remainder > 0 ? totalNum / 10 + 1 : totalNum / 10;
             for (int i = 0; i < 10; i++) {
                 int page = i * size;
                 Future<List<T>> pv = threadAsyncTableDataQuery.selectTableDataAsync(page, size);
                 list.add(pv);
             }
         } else {
             Future<List<T>> ts = threadAsyncTableDataQuery.selectTableDataAsync(0, 50000);
             list.add(ts);
         }
         return this.taskValue(list);
     }

     /**
      * 拿取线程里的数据
      *
      * @param taskFutures
      * @return
      */
     public   List<T> taskValue(List<Future<List<T>>> taskFutures) {
         List<T> result = new ArrayList<>();
         try {
             for (Future<List<T>> future : taskFutures) {
                 List<T> obj = future.get();
                 if (null != obj) {
                     result.addAll(obj);
                 }
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         return result;
     }




}
